package controller

import (
	"awesomeProject/goprpoject/test11/common"
	"awesomeProject/goprpoject/test11/dto"
	"awesomeProject/goprpoject/test11/model"
	"awesomeProject/goprpoject/test11/response"
	"awesomeProject/goprpoject/test11/util"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
)

func Register(c *gin.Context) {

	DB := common.GetBD()
	// 你可以显式声明来绑定多媒体表单：
	// c.BindWith(&form, binding.Form)
	// 或者使用自动推断:

	// 获取参数
	// 方法1：
	// var requestMap = make(map[string]string)
	// json.NewDecoder(c.Request.Body).Decode(&requestMap)

	// 方法二：使用结构体
	// var requestUser = model.Users{}
	// json.NewDecoder(c.Request.Body).Decode(&requestUser)

	// 方法三：gin 框架 json
	var requestUser = model.Users{}
	c.Bind(&requestUser)
	name := requestUser.Name
	tel := requestUser.Tel
	passWord := requestUser.PassWord

	// 方法四：form-data
	// name := c.PostForm("name")
	// tel := c.PostForm("tel")
	// passWord := c.PostForm("password")
	// 数据验证
	if len(tel) != 11 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "手机号码必须是11位数")
		//c.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "手机号码必须是11位数"})
		return

	}
	if len(passWord) < 6 {

		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位数")
		//c.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "密码不能少于6位数"})
		return
	}
	// 随机字符串
	if len(name) == 0 {

		name = util.RandomString(10)

	}
	log.Println(name, tel, passWord)
	// 查询手机号码 判断是否存在

	if isTelExist(DB, tel) {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户已经注册")
		//c.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "用户已经注册"})
		return
	}
	// 新建用户
	hasedPassword, err := bcrypt.GenerateFromPassword([]byte(passWord), bcrypt.DefaultCost)
	if err != nil {
		response.Response(c, http.StatusUnprocessableEntity, 500, nil, "加密错误")
		//c.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "加密错误"})
		return
	}
	newUser := model.Users{
		Name:     name,
		Tel:      tel,
		PassWord: string(hasedPassword)}
	// 入库c
	DB.Create(&newUser)
	// 返回结果

	// c.JSON(http.StatusOK, gin.H{c
	// 	"code": "200",
	// 	"msg":  "注册成功",
	// 	"data": name,
	// })
	// response.Response(c, http.StatusUnprocessableEntity, 500, nil, "加密错误")
	// 发放token
	token, err := common.ReleaseToken(newUser)
	if err != nil {
		response.Response(c, http.StatusUnprocessableEntity, 500, nil, "系统异常")
		//ctx.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "系统异常token签发失败"})
		log.Printf("token genrate error")
		return
	}
	response.Success(c, gin.H{"token": token}, "注册成功")
	//response.Success(c, nil, "注册成功")
}

func isTelExist(db *gorm.DB, tel string) bool {

	var user model.Users
	db.Where("tel = ?", tel).First(&user)
	if user.ID != 0 {
		return true
	}
	return false
}

func Login(ctx *gin.Context) {
	DB := common.GetBD()
	// 获取参数
	tel := ctx.PostForm("tel")
	pwd := ctx.PostForm("pwd")

	// 数据验证

	if len(tel) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 500, nil, "手机号码必须是11位数")
		//ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "手机号码必须是11位数"})
		return

	}
	if len(pwd) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位数")
		//ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "密码不能少于6位数"})
		return
	}
	// 判断手机号是否存在
	var user model.Users
	DB.Where("tel=?", tel).First(&user)
	if user.ID == 0 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		//ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "用户不存在"})
		return
	}
	// 判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.PassWord), []byte(pwd)); err != nil {
		response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "密码输入有误")
		//ctx.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "密码输入有误"})

		//
		return
	}
	// 发放token
	token, err := common.ReleaseToken(user)
	if err != nil {
		response.Response(ctx, http.StatusUnprocessableEntity, 500, nil, "系统异常")
		//ctx.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "系统异常token签发失败"})
		log.Printf("token genrate error")
		return
	}

	// 返回结果
	// ctx.JSON(http.StatusOK, gin.H{
	// 	"code": 200,
	// 	"msg":  "登录成功",
	// 	"data": gin.H{"token": token}})
	response.Success(ctx, gin.H{"token": token}, "登录成功")
}

func Info(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	ctx.JSON(http.StatusOK, gin.H{"code": 200, "data": gin.H{"user": dto.ToUserDto(user.(model.Users))}}) // 返回指定的字段 类类型断言

}
